package dk.Utils;

import java.io.File;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;

//这是腾讯cos存储的工具类
public class COSUtils {
	private static final String ACCESSKEY = "";
    private static final String SECRETKEY ="";
    private static final String BUCKETNAME = "misaka917-1301164487";
    private static final String APPID = "1301164487";
    private static final String REGIONID = "ap-nanjing";
    //生成对象
    public static COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(ACCESSKEY, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        //String bucketName = BUCKETNAME;
        return cosClient;
    }
    //上传文件 地址上传
    public static int uploadFileByPath(String Path,String CloudPath) {
    	File localFile = new File(Path);
    	String KEY = CloudPath;
    	PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, KEY, localFile);
    	 // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        COSClient cc = getCosClient();
        try {
            PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
            System.out.println(etag);
            return 1;
        } catch (CosServiceException e) {
        	
            e.printStackTrace();
            return 0;
        } catch (CosClientException e) {
            e.printStackTrace();
            return 0;
        }
        // 关闭客户端
        finally {
        	 cc.shutdown();
             
        }
       
    }
    //删除
    public static int DeleteObjectByCloudPath(String CloudPath) {
    	COSClient cc = getCosClient();
    	try {
    		cc.deleteObject(BUCKETNAME, CloudPath);
    		return 1;
    	}
           catch (CosServiceException e) {
        	
            e.printStackTrace();
            return 0;
        } catch (CosClientException e) {
            e.printStackTrace();
            return 0;
        }
    	finally {
    		cc.shutdown();
    	}
    }

    
}
